<template>
  <div
    v-if="isShow"
    class="container"
    :style="
      Object.assign(singleComponentSizeScale, singleComponentPaddingConfigStyle)
    "
  >
    <div class="title">{{ title }}</div>
    <div class="close-button" @click="close"></div>
    <div class="search-box">
      <span class="description">图层</span>
      <el-select
        v-model="currentSelectedLayer"
        placeholder="请选择图层"
        :popper-append-to-body="false"
        @change="selectedLayerChangeHandle"
      >
        <el-option
          v-for="item in layerList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </div>
    <div class="list">
      <div v-if="loading" class="loading">
        <div class="spinner">
          <svg viewBox="25 25 50 50" class="circular">
            <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
          </svg>
        </div>
      </div>
      <ul v-if="currentSelectedLayerResourceList.length">
        <li
          v-for="(item, index) in currentSelectedLayerResourceList"
          :key="index"
        >
          <div class="first-line">
            <span
              class="name span-ellipsis"
              :class="item.status && item.status !== '2' ? 'name-special' : ''"
              :title="
                dynamicallyCreateSpecialNameForPOIOfCamera(
                  item.name,
                  item.status || ''
                )
              "
              >{{
                dynamicallyCreateSpecialNameForPOIOfCamera(
                  item.name,
                  item.status || ''
                )
              }}</span
            >
            <div class="label">{{ item.layerName }}</div>
          </div>
          <div class="second-line">
            <span
              class="address span-ellipsis"
              :title="item.address || '暂无地址'"
            >
              <i class="el-icon-location-outline"></i>
              {{ item.address || '暂无地址' }}
            </span>
          </div>
          <div class="second-line">
            <i class="el-icon-user-solid"></i>
            <span>联系人：</span>
            <span :title="item.contactPerson || '暂无'">{{
              item.contactPerson || '暂无'
            }}</span>
            <i class="el-icon-phone icon-special"></i>
            <span>联系方式：</span>
            <span :title="item.desensitizeContactPhone || '暂无'">{{
              item.desensitizeContactPhone || '暂无'
            }}</span>
            <div class="row-button">
              <img
                v-if="item.cameraCode || item.contactPhone"
                title="指挥调度"
                :src="deployIcon"
                @click="commandAndDeploy(item)"
              />
              <img
                v-if="item.contactPhone"
                title="语音通话"
                :src="phoneIcon"
                @click="
                  voiceCall(item.contactPhone, item.contactPerson || item.name)
                "
              />
              <img
                class="img-special"
                v-if="item.cameraCode"
                title="实时视频"
                :src="cameraIcon"
                @click="showVideo(item.cameraCode)"
              />
            </div>
          </div>
        </li>
      </ul>
      <div v-else class="empty">暂无数据</div>
    </div>
    <div class="container-bottom-outer"></div>
  </div>
</template>

<script>
import { componentSizeScale, desensitizeTeL } from '@utils'
import { getPOIDataByParams } from '@api/common'
import { cameraDetail } from '@api/dailyDispatching'
import deployIcon from './images/button-icon-deploy.png'
import phoneIcon from './images/button-icon-phone.png'
import cameraIcon from './images/button-icon-camera.png'

export default {
  name: 'SurroundingSearchResources',
  props: {
    // 图形搜索信息 TODO: 参数名称待调整/功能待扩充
    searchCircle: {
      type: Object,
      required: true,
      default: {}
    },
    // 搜索结果按图层展示的图层首选项自定义设置
    searchResultPreferenceCustomSetting: {
      type: Number,
      required: false,
      default: 0 // 默认值为0，可用值：0-全部图层；1-首图层
    }
  },
  data() {
    return {
      deployIcon: deployIcon,
      phoneIcon: phoneIcon,
      cameraIcon: cameraIcon,
      topicType: this.$route.query.topicType || this.$route.meta.code,
      originalDesignSize: {
        width: 7680,
        height: 2160
      }, // 组件设计尺寸基准数值(同大屏原始设计尺寸保持一致)
      title: '周边资源',
      isShow: false,
      loading: false,
      currentSelectedLayer: '', // 当前选中图层参数
      layerList: [], // 图层列表数组参数
      currentSelectedLayerResourceList: [], // 当前选中图层对应的资源列表数组参数
      searchResult: {} // 存储搜索结果对象参数
    }
  },
  computed: {
    // 动态计算组件尺寸缩放比例
    singleComponentSizeScale: function() {
      const scale = componentSizeScale(
        this.originalDesignSize.width,
        this.originalDesignSize.height
      )
      return {
        '--scaleX': scale.scaleX,
        '--scaleY': scale.scaleY,
        '--scaleRelative': scale.scaleRelative,
        '--scaleFontRelative': scale.scaleFontRelative
      }
    },
    // 动态计算组件四周空隙留白(padding)样式
    singleComponentPaddingConfigStyle: function() {
      return {
        '--paddingTop':
          _const.mapConfigInfo.effectConfig.componentPaddingConfig.top,
        '--paddingRight':
          _const.mapConfigInfo.effectConfig.componentPaddingConfig.right,
        '--paddingBottom':
          _const.mapConfigInfo.effectConfig.componentPaddingConfig.bottom,
        '--paddingLeft':
          _const.mapConfigInfo.effectConfig.componentPaddingConfig.left
      }
    }
  },
  watch: {
    // 监听传入查询对象参数，用于查询数据
    searchCircle(param) {
      let { radius, lat, lng, layerIdList } = param
      // 特殊的，针对存在指定图层查询情况添加指定逻辑
      if (layerIdList) {
        const prescriptiveLayerId = _const.cameraLayerId // 指定的图层id，当前为视频监控图层
        layerIdList.unshift(prescriptiveLayerId) // 添加至查询图层数组参数最前，用于查询结果图层的首位展示
      }
      this.getSearchResult(radius, lat, lng, layerIdList)
    }
  },
  methods: {
    // 获取搜索结果
    getSearchResult(radius, lat, lng, layerIdList) {
      this.isShow = true
      this.loading = true
      const params = {
        topicType: this.topicType,
        needGroup: false,
        circleRadius: radius,
        circlePoint: {
          fragment: true,
          geohash: '',
          lat: lat,
          lon: lng
        }
      }
      if (layerIdList) params.layerIdList = layerIdList
      getPOIDataByParams(params)
        .then(res => {
          if (res.success) this.formatAndShowSearchResult(res.result)
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 格式化并个性化展示搜索结果数据
    formatAndShowSearchResult(data) {
      this.layerList = []
      if (data === null) {
        this.currentSelectedLayer = undefined
        this.currentSelectedLayerResourceList = []
        return
      }
      if (Object.keys(data).length > 1) {
        this.layerList.push({
          name: '全部',
          id: ''
        })
      }
      // 遍历返回数据，进行图层列表初始化构建和搜索结果数据格式化
      Object.keys(data).forEach(key => {
        // 图层列表初始化构建
        this.layerList.push({
          id: key,
          name: data[key][0].layerName
        })
        // 搜索结果数据格式化
        data[key].map(item => {
          item.desensitizeContactPhone = desensitizeTeL(item.contactPhone) // 添加手机号码脱敏处理的字段
        })
      })
      this.searchResult = data
      // 根据配置，指定默认首选图层
      let defaultSelectedLayerIndex = 0
      if (
        this.searchResultPreferenceCustomSetting &&
        Object.keys(data).length > 1
      ) { defaultSelectedLayerIndex = 1 }
      this.currentSelectedLayer = this.layerList[defaultSelectedLayerIndex].id
      this.selectedLayerChangeHandle(this.currentSelectedLayer) // 手动触发图层选中变化事件响应
    },
    // 图层选中变化事件响应
    selectedLayerChangeHandle(layerId) {
      this.currentSelectedLayerResourceList = []
      for (let key in this.searchResult) {
        if (key === layerId) {
          this.currentSelectedLayerResourceList = this.searchResult[layerId]
          break
        } else {
          this.currentSelectedLayerResourceList = [
            ...this.currentSelectedLayerResourceList,
            ...this.searchResult[key]
          ]
        }
      }
    },
    // 动态生成监控设备类POI(根据设备状态)名称
    dynamicallyCreateSpecialNameForPOIOfCamera(name, status) {
      let spliceString = ''
      switch (status) {
        case '2':
          spliceString = '(在线)'
          break
        case '1':
        case '3':
        case '4':
          spliceString = '(离线)'
          break
      }
      return name + spliceString
    },
    // 指挥调度按钮点击响应
    commandAndDeploy(data) {
      let param = {}
      // 区分视频(监控)和电话(联系方式)两种调度类型,优先进行视频(监控)调度,其次为电话(联系方式)调度
      if (data.cameraCode) {
        param = {
          eventBusType: 'camera',
          cameraCode: data.cameraCode,
          cameraName: data.cameraName || data.name
        }
      } else if (data.contactPhone) {
        param = {
          eventBusType: 'person',
          contactPersonPhoneNumber: data.contactPhone,
          contactPersonName: data.contactPerson || data.name
        }
      } else return
      this.$eventBus.$emit('addToMeetting', param) // 向指挥调度面板发送指令
    },
    // 语音通话按钮点击响应
    voiceCall(telephoneNumber, contactPersonName) {
      const param = {
        telephone: telephoneNumber,
        name: contactPersonName
      }
      this.$eventBus.$emit('singleCall', param) // 向单点通话面板发送指令
    },
    // 实时视频按钮点击响应
    showVideo(code) {
      this.loading = true
      cameraDetail({ cameraCode: code })
        .then(res => {
          if (res.success) {
            this.$eventBus.$emit('showVideoDialog', res.result.playUrl.flvUrl, {
              cameraCode: code
            })
          } else this.$message.warning('该视频监控已下线')
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 关闭按钮点击事件响应
    close() {
      this.isShow = false
      this.currentSelectedLayer = ''
      this.layerList = []
      this.currentSelectedLayerResourceList = []
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: calc(755px * var(--scaleX));
  max-height: calc(1007px * var(--scaleY));
  padding: 0 calc(26px * var(--scaleX)) calc(20px * var(--scaleY));
  position: absolute;
  top: calc(500px * var(--scaleY));
  right: calc(var(--paddingRight) + 80px * var(--scaleX));
  color: #ffffff;
  border: #20cbff calc(4px * var(--scaleRelative)) solid;
  background: #0c183ccc;
  z-index: 3;
  cursor: default;
  .close-button {
    width: calc(31px * var(--scaleX));
    height: calc(30px * var(--scaleY));
    position: absolute;
    top: calc(20px * var(--scaleY));
    right: calc(40px * var(--scaleX));
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-image: url('./images/button-icon-close.png');
    cursor: pointer;
  }
  .title {
    margin-top: calc(20px * var(--scaleY));
    padding: calc(15px * var(--scaleY)) 0 calc(10px * var(--scaleY));
    text-align: center;
    font-size: calc(35px * var(--scaleFontRelative));
    font-weight: bold;
    border-bottom: #20c8ff calc(4px * var(--scaleY)) solid;
  }
  .search-box {
    margin-top: calc(20px * var(--scaleY));
    font-size: calc(30px * var(--scaleFontRelative));
    display: flex;
    align-items: center;
    justify-content: space-between;
    .description {
      margin-left: calc(5px * var(--scaleX));
    }
    ::v-deep .el-select {
      cursor: pointer;
      .el-input {
        input {
          width: calc(600px * var(--scaleX));
          height: calc(52px * var(--scaleY));
          padding-right: calc(10px * var(--scaleX));
          color: #00e4ff;
          font-size: calc(28px * var(--scaleFontRelative));
          font-family: Source Han Sans CN;
          font-weight: 400;
          border: #0ac2ed calc(2px * var(--scaleRelative)) solid;
          background: linear-gradient(180deg, #2ba8ff4d 0%, #0c183c 84%);
        }
        .el-input__icon {
          line-height: calc(40px * var(--scaleY));
        }
      }
      .el-tag.el-tag--info {
        height: calc(38px * var(--scaleY));
        font-size: calc(25px * var(--scaleFontRelative));
        background-color: #00ffff00;
        border-color: #02cde9;
        color: #02cde9;
        .el-tag__close {
          background-color: #00e4ff;
        }
      }
      .el-select__tags {
        max-width: 100% !important;
      }
      .el-input__inner::placeholder {
        color: #00e4ff;
      }
      .el-select-dropdown {
        border: #00e4ff calc(2px * var(--scaleRelative)) solid;
        background: #11254b;
        width: 100%;
        top: calc(42px * var(--scaleY)) !important;
        .el-select-dropdown__item {
          height: calc(43px * var(--scaleY));
          line-height: calc(43px * var(--scaleY));
          color: #00e4ff;
          font-size: calc(28px * var(--scaleFontRelative));
        }
        .el-select-dropdown__item.selected,
        .el-select-dropdown__item:hover {
          color: #fabe00;
          background: transparent;
        }
        .hover {
          background: transparent;
        }
        .popper__arrow {
          display: none !important;
        }
      }
      .el-icon-arrow-up:before {
        font-size: calc(20px * var(--scaleFontRelative));
        color: #00e4ff;
        content: '\e78f';
      }
      .el-icon-arrow-down:before {
        font-size: calc(20px * var(--scaleFontRelative));
        color: #00e4ff;
        content: '\e790';
      }
    }
  }
  .list {
    width: 100%;
    height: auto;
    max-height: calc(792px * var(--scaleY));
    margin-top: calc(20px * var(--scaleY));
    overflow-y: auto;
    overflow-x: hidden;
    .loading {
      width: calc(100% - 50px * var(--scaleX));
      height: calc(100% - 202px * var(--scaleY));
      position: absolute;
      background: #0d76f20d;
      display: flex;
      align-items: center;
      justify-content: center;
      .spinner {
        .circular {
          height: calc(110px * var(--scaleRelative));
          width: calc(110px * var(--scaleRelative));
          -webkit-animation: loading-rotate 2s linear infinite;
          animation: loading-rotate 2s linear infinite;
        }
        .path {
          animation: loading-dash 1.5s ease-in-out infinite;
          stroke-dasharray: 90, 150;
          stroke-dashoffset: 0;
          stroke-width: 2;
          stroke: #409eff;
          stroke-linecap: round;
        }
        @keyframes loading-dash {
          0% {
            stroke-dasharray: 1, 200;
            stroke-dashoffset: 0;
          }
          50% {
            stroke-dasharray: 90, 150;
            stroke-dashoffset: calc(-40px * var(--scaleRelative));
          }
          100% {
            stroke-dasharray: 90, 150;
            stroke-dashoffset: calc(-120px * var(--scaleRelative));
          }
        }
        @keyframes loading-rotate {
          100% {
            transform: rotate(360deg);
          }
        }
      }
    }
    & > ul {
      font-size: calc(34px * var(--scaleFontRelative));
      & > li {
        padding: calc(20px * var(--scaleY)) 0;
        border-bottom: calc(2px * var(--scaleY)) solid;
        border-image: linear-gradient(
            90deg,
            #00d8f700 0%,
            #00afed 50%,
            #00d8f700 100%
          )
          2;
        &:hover {
          color: #f1f2f7;
          background: linear-gradient(0deg, #f7ab00 0%, #ffffff 100%);
          background-clip: text;
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          border-image: linear-gradient(
              90deg,
              #ffffff00 0%,
              #ffb300 50%,
              #ffffff00 100%
            )
            2;
        }
        .first-line {
          display: flex;
          & > span {
            display: inline-block;
          }
          .label {
            width: auto;
            margin-right: calc(60px * var(--scaleX));
            padding: 0 calc(12px * var(--scaleX));
            font-size: calc(24px * var(--scaleFontRelative));
            color: #ffffff;
            border: #20c8ff calc(4px * var(--scaleRelative)) solid;
            border-radius: calc(10px * var(--scaleRelative));
          }
          .name {
            margin-right: calc(10px * var(--scaleX));
            font-size: calc(34px * var(--scaleFontRelative));
            font-weight: bold;
            letter-spacing: calc(2px * var(--scaleX));
            flex: 3;
          }
          .name-special {
            color: #ababab;
          }
        }
        .second-line {
          font-size: calc(28px * var(--scaleFontRelative));
          color: #d0deee;
          font-weight: 400;
          & > span {
            max-width: calc(170px * var(--scaleX));
            display: inline-block;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
          }
          .area {
            max-width: calc(140px * var(--scaleX));
            margin-right: calc(30px * var(--scaleX));
          }
          .address {
            max-width: calc(510px * var(--scaleX));
          }
          .icon-special {
            margin-left: calc(30px * var(--scaleX));
          }
          .row-button {
            display: flex;
            & > img {
              width: calc(40px * var(--scaleX));
              height: calc(40px * var(--scaleY));
              margin-left: calc(20px * var(--scaleX));
              cursor: pointer;
              &:hover {
                transform: scale(1.1);
              }
            }
            .img-special {
              width: calc(42px * var(--scaleX));
              height: calc(43px * var(--scaleY));
              margin-top: calc(-1px * var(--scaleY));
            }
          }
        }
        .first-line,
        .second-line {
          height: calc(52px * var(--scaleY));
          display: flex;
          align-items: center;
        }
        .span-ellipsis {
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }
      }
    }
    .empty {
      height: calc(200px * var(--scaleY));
      font-size: calc(30px * var(--scaleFontRelative));
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .container-bottom-outer {
    transform: rotate(90deg);
    width: calc(156px * var(--scaleX));
    height: 0;
    position: absolute;
    top: calc(80px * var(--scaleY));
    left: calc(-86px * var(--scaleX));
    border-top: #20cbff calc(12px * var(--scaleY)) solid;
    border-left: transparent calc(20px * var(--scaleX)) solid;
    border-right: transparent calc(20px * var(--scaleX)) solid;
  }
  ::v-deep ::-webkit-scrollbar {
    width: calc(10px * var(--scaleX));
    height: calc(10px * var(--scaleY));
    background-color: #06376f;
  }
  ::v-deep ::-webkit-scrollbar-track {
    border-radius: calc(10px * var(--scaleRelative));
    background-color: #3d6bff;
  }
  ::v-deep ::-webkit-scrollbar-thumb {
    border-radius: calc(4px * var(--scaleRelative));
    -webkit-box-shadow: inset 0 0 6px #0000004d;
    background-color: #25deff;
  }
}
</style>
